var app = new Vue({
  el: "#app",
  data: {
    tabActiveTime: 0,
    tabListTime: [
      { id: 0, label: "今天" },
      { id: 1, label: "昨天" },
      { id: 2, label: "最近7天" },
      { id: 3, label: "最近30天" },
    ],
    dateRange: "",
    time: "",
    tabActiveShowType: 1,
    tabActiveTimeType: 1,
    tabListTimeType: [
      { id: 1, label: "日" },
      { id: 2, label: "周" },
      { id: 3, label: "月" },
    ],
    filterForm: {
      push_channel: "2",
      msg_type: "1",
      crm_push_mans: "",
    },
    infoTable: {
      list: [],
      loading: false,
    },
    detailTable: {
      list: [],
      total: 0,
      pageNumber: 1,
      pageSize: 10,
      loading: false,
    },
    manList: [],
  },
  mounted() {
    this.init();
  },
  watch: {
    time: {
      handler() {
        this.getInfo();
      },
      deep: true,
    },
  },
  methods: {
    init() {
      this.tabActiveTime = 0;
      this.handleChange(0);
      this.getSelectInfo();
    },
    getSelectInfo() {
      apiGetManList().then((res) => {
        this.manList = res.data;
      });
    },

    handleChange(value) {
      const today = new Date();
      if (value === 0) {
        this.time = {
          start: today,
          end: today,
        };
      } else if (value === 1) {
        this.time = {
          start: this.getDay(-1),
          end: this.getDay(-1),
        };
      } else if (value === 2) {
        this.time = {
          start: this.getDay(-6),
          end: today,
        };
      } else if (value === 3) {
        this.time = {
          start: this.getDay(-29),
          end: today,
        };
      }
      this.dateRange = [this.time.start, this.time.end];
    },
    handleRangeChange(value) {
      if (!value) {
        this.tabActiveTime = 0;
        this.handleChange(0);
        return;
      }
      this.time = {
        start: value[0],
        end: value[1],
      };
      this.tabActiveTime = -1;
    },
    handleTimeTypeChange() {
      this.getInfo();
    },
    getDay(day) {
      var today = new Date();
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds); //注意，这行是关键代码
      return today;
    },
    formatDate(value = Date.now(), format = "Y-M-D h:m:s") {
      const formatNumber = (n) => `0${n}`.slice(-2);
      const date = new Date(value);
      const formatList = ["Y", "M", "D", "h", "m", "s"];
      const resultList = [];
      resultList.push(date.getFullYear().toString());
      resultList.push(formatNumber(date.getMonth() + 1));
      resultList.push(formatNumber(date.getDate()));
      resultList.push(formatNumber(date.getHours()));
      resultList.push(formatNumber(date.getMinutes()));
      resultList.push(formatNumber(date.getSeconds()));
      for (let i = 0; i < resultList.length; i++) {
        format = format.replace(formatList[i], resultList[i]);
      }
      return format;
    },
    handleShowTypeClick(value) {
      this.tabActiveShowType = value;
      this.getInfo();
    },
    getInfo() {
      if (this.tabActiveShowType === 1) {
        // 推送汇总
        this.getInfoList("init");
      } else if (this.tabActiveShowType === 2) {
        // 推送详情
        this.getInfoList("init");
      } else if (this.tabActiveShowType === 3) {
        // 消息详情
        this.getDetailList("init");
      }
    },
    // 获取列表
    getInfoList(type) {
      if (type !== "init") {
        this.infoTable.pageNumber = 1;
      }
      this.infoTable.loading = true;
      apiGetInfoList({
        start_time: this.formatDate(this.time.start, "Y-M-D"),
        end_time: this.formatDate(this.time.end, "Y-M-D"),
        push_channel: this.filterForm.push_channel,
        msg_type: this.filterForm.msg_type,
        crm_push_mans: this.filterForm.crm_push_mans,
        time_type: this.tabActiveTimeType,
      })
        .then((res) => {
          const { data } = res;
          this.infoTable.list = data;
          this.infoTable.loading = false;
          if (this.tabActiveShowType === 1) {
            this.$refs.infoTable && this.$refs.infoTable.doLayout();
          } else if (this.tabActiveShowType === 2) {
            this.$nextTick(() => {
              this.initChart();
            });
          }
        })
        .catch((err) => {
          this.infoTable.list = [];
          this.infoTable.loading = false;
          this.$message.error((err && err.msg) || err);
        });
    },
    // 获取详情列表
    getDetailList(type) {
      if (type !== "init") {
        this.detailTable.pageNumber = 1;
      }
      this.detailTable.loading = true;
      apiGetDetailList({
        pageNumber: this.detailTable.pageNumber,
        pageSize: this.detailTable.pageSize,
        start_time: this.formatDate(this.time.start, "Y-M-D"),
        end_time: this.formatDate(this.time.end, "Y-M-D"),
        push_channel: this.filterForm.push_channel,
        msg_type: this.filterForm.msg_type,
        time_type: this.tabActiveTimeType,
      })
        .then((res) => {
          const { data, total } = res;
          this.detailTable.list = data;
          this.detailTable.total = total;
          this.detailTable.loading = false;
          this.$refs.detailTable && this.$refs.detailTable.doLayout();
        })
        .catch((err) => {
          this.detailTable.list = [];
          this.detailTable.total = 0;
          this.detailTable.loading = false;
          this.$message.error((err && err.msg) || err);
        });
    },
    initChart() {
      this.chart = echarts.init(document.getElementById("echarts"));
      this.setOptions(this.infoTable.list);
    },
    setOptions(chartData) {
      if (!this.chart) {
        return;
      }
      let option = {};
      let color = [
        "#4874cb",
        "#ee822f",
        "#f2ba02",
        "#75bd42",
        "#30c0b4",
        "#e54c5e",
      ];
      if (!chartData || chartData.length === 0) {
        option = {
          xAxis: {
            data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            boundaryGap: false,
            axisTick: {
              show: false,
            },
          },
          color,
          grid: {
            left: 20,
            right: 20,
            bottom: 20,
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
            padding: [5, 10],
          },
          yAxis: {
            // 整条y轴
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
          legend: {
            data: ["暂无数据"],
          },
          series: [
            {
              name: "暂无数据",
              smooth: true,
              type: "line",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              animationDuration: 1000,
              animationEasing: "cubicInOut",
            },
          ],
        };
      } else {
        const legend = [
          {
            name: "推送生意信息数量（人次）",
            dataName: "push_people",
            type: "bar",
          },
          {
            name: "推送成功数量",
            dataName: "push_success",
            type: "bar",
          },
          {
            name: "用户查看数量",
            dataName: "view_num",
            type: "line",
          },
          {
            name: "读取率",
            dataName: "read_rate",
            type: "line",
          },
          {
            name: "采纳率",
            dataName: "accept_rate",
            type: "line",
          },
        ];
        const xAxis = chartData.map((item) => item.date);
        const series = [];
        legend.forEach((item) => {
          series.push({
            name: item.name,
            data: chartData.map((item1) => item1[item.dataName]),
            type: item.type,
            smooth: true,
            animationDuration: 1000,
            animationEasing: "cubicInOut",
            barWidth: "10%",
            yAxisIndex: item.type === "line" ? 1 : 0,
          });
        });
        option = {
          tooltip: {},
          legend: {
            data: legend.map((item) => item.name),
          },
          color,
          xAxis: {
            data: xAxis,
            axisTick: {
              show: false,
            },
          },
          series: series,
          grid: {
            left: 20,
            right: 20,
            bottom: 20,
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
            padding: [5, 10],
          },
          yAxis: [
            {
              type: "value",
              axisTick: {
                show: false,
              },
              axisLine: {
                show: false,
              },
            },
            {
              type: "value",
              min: 0,
              max: 120,
              interval: 20,
              axisLabel: {
                formatter: "{value}%",
              },
              axisTick: {
                show: false,
              },
              axisLine: {
                show: false,
              },
            },
          ],
        };
      }

      this.chart.setOption(option, true);
    },
    onResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.detailTable.pageSize = val;
      this.detailTable.pageNumber = 1;
      this.getDetailList("init");
    },
    // 当前页
    currentChangeHandle(val) {
      this.detailTable.pageNumber = val;
      this.getDetailList("init");
    },
  },
});
